package my.springboot.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import my.springboot.domain.primary.Dict;
import my.springboot.domain.primary.MqTransaction;
import my.springboot.service.MqTransactionService;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fengbo
 */
//@Component
public class TransactionListenerImpl implements TransactionListener {

    @Autowired
    private MqTransactionService mqTransactionService;

    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        String bizUniNo = message.getTransactionId();
        mqTransactionService.saveMsg((Dict) o, bizUniNo);
        return LocalTransactionState.UNKNOW;
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        String bizUniNo = messageExt.getTransactionId();
        MqTransaction value = mqTransactionService.getOne(new LambdaQueryWrapper<MqTransaction>().eq(MqTransaction::getMsgKey, bizUniNo));
        if (value != null && bizUniNo.equals(value.getMsgKey())) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        return LocalTransactionState.ROLLBACK_MESSAGE;
    }
}
